package com.egene.zh.utils;

import android.text.TextUtils;
import android.util.Log;

import com.egene.zh.model.net.ResponseBean;
import com.egene.zh.model.net.ResponseList;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.lang.reflect.Type;

public class JsonUtil {
	private static final String TAG = "JsonUtil";

	public static final <T> T parse(String json, Class<T> type) {
		if (TextUtils.isEmpty(json)) {
			return null;
		}
		T result = null;
		try {
			result = new Gson().fromJson(json, type);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "解析json为 " + type.getName() + " 失败  " + json);
			return null;
		}
		return result;
	}

	public static final <T> T parse(byte[] arg, Class<T> type) {
		return parse(new String(arg), type);
	}

	public static final <T> ResponseList<T> toList(byte[] arg, Type type) {
		// new TypeToken<NetLifeServiceDesc>(){}.getType()
		// Type collectionType = new TypeToken<NetResultList<T>>(){}.getType();
		ResponseList<T> result;
		try {
			result = new Gson().fromJson(new String(arg), type);
		} catch (JsonSyntaxException e){
			e.printStackTrace();
			Log.e(TAG, "解析json为 " + type.toString() + " 失败  " + new String(arg));
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "解析json为 " + type.toString() + " 失败  " + new String(arg));
			return null;
		}
		return result;
	}

	public static final <T> ResponseBean<T> toBean(byte[] arg, Type type) {
		ResponseBean<T> result;
		try {
			result = new Gson().fromJson(new String(arg), type);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "解析json为 " + type.toString() + " 失败  " + new String(arg));
			return null;
		}
		return result;
	}
}
